package com.hmdp.utils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class RedisCache {

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * set hash for key
     *
     * @param key
     * @param field
     * @param value
     */
    public void setHash(String key, String field, Object value) {
        redisTemplate.opsForHash().put(key, field, value);
    }

    /**
     * set hash for key
     *
     * @param key
     * @param map
     */
    public void setHash(String key, Map map) {
        redisTemplate.opsForHash().putAll(key, map);
    }

    /**
     * set hash for key
     *
     * @param key
     * @param map
     * @param expireTime
     * @param timeUnit
     */
    public void setHash(String key, Map map, Long expireTime, TimeUnit timeUnit) {
        redisTemplate.opsForHash().putAll(key, map);
        redisTemplate.expire(key, expireTime, timeUnit);
    }

    public Map getHash(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    public void expire(String key, Long expireTime, TimeUnit timeUnit) {
        redisTemplate.expire(key, expireTime, timeUnit);
    }

    public <T> void setValue(String key, final T value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public <T> void setValue(String key, final T value, Long loginCodeTtl, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, loginCodeTtl, timeUnit);
    }

    public <T> T getValue(String key) {
        ValueOperations<String, T> operations = redisTemplate.opsForValue();
        return operations.get(key);
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }

}
